package com.ycwl.library;

import android.content.Context;
import android.os.Build;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.ycwl.freetv.AdActivity;
import com.ycwl.freetv.program.Program;
import com.ycwl.freetv.utils.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

public class AssetsListManager {
    private final static String TAG = "AssetsListManager";
    private final static AssetsListManager instance = new AssetsListManager();

    public static AssetsListManager getInstance() {
        return instance;
    }

    public int getProgramIndex() {
        return programIndex;
    }

    public void setProgramIndex(int programIndex) {
        this.programIndex = programIndex;
    }

    public final static class Assets {
        public String sha1;
        // 文件绝对路径
        public String path;
        public String name;
        // 根据这个字段判断是否需要删除资源
        public int quote;

        public Assets(String sha1, String path, String name) {
            this.sha1 = sha1;
            this.path = path;
            this.name = name;
            this.quote = 0;
        }
    }

    HashMap<String, Assets> assetsHashMap;

    public ParseUIFromJson.MPlayList getmPlayList() {
        return mPlayList;
    }

    public void setmPlayList(ParseUIFromJson.MPlayList mPlayList) {
        this.mPlayList = mPlayList;
    }


    ParseUIFromJson.MPlayList mPlayList = null;
    int programIndex = 0;


    public String getConfigFilePath() {
        return configFilePath;
    }

    String configFilePath;

    public String getAssetsCachePath() {
        return assetsCachePath;
    }

    String assetsCachePath;

    private AssetsListManager() {
        assetsHashMap = new HashMap<>();
    }

    public void init(Context context) {
        this.assetsCachePath = context.getApplicationContext().getCacheDir().getAbsolutePath() + File.separator + "assets";
        this.configFilePath = context.getApplicationContext().getCacheDir().getAbsolutePath() + File.separator + "config";
        File file = new File(this.assetsCachePath);
        if (!file.exists()) {
            if (!file.mkdir()) {
                Log.e(TAG, "create dir fail ! " + this.assetsCachePath);
            }
        }
        File fileAssets = new File(this.configFilePath);
        if (!fileAssets.exists()) {
            if (!fileAssets.mkdir()) {
                Log.e(TAG, "create dir fail ! " + this.configFilePath);
            }
        }

    }

    public void addAssets(Assets assets) {
        if (!assetsHashMap.containsKey(assets.sha1)) {
            assetsHashMap.put(assets.sha1, assets);
        }
    }

    public Assets getAssetsByHash(String sha1) {
        if (assetsHashMap.containsKey(sha1)) {
            return assetsHashMap.get(sha1);
        }
        return null;
    }

    public void incAssetsQuote(String key) {
        if (assetsHashMap.containsKey(key)) {
            assetsHashMap.get(key).quote++;
        }
    }

    public void importAssetsByDir(String path, int deep) {
        if (deep <= 0) {
            return;
        }
        File file = new File(path);
        if (file.exists()) {
            importAssetsByDir(file, deep);
        }
    }

    public void importAssetsByDir(File directory, int deep) {
        if (deep <= 0 || directory == null) {
            return;
        }

        if (!directory.exists() || !directory.isDirectory()) {
            return;
        }
        File[] fileArray = directory.listFiles();
        // 空文件夹直接删除
        if (fileArray == null) {
            FileUtils.deleteFile(directory);
            return;
        }
        for (File file : fileArray) {
            String name = file.getName();
            if (file.isDirectory()) {
                importAssetsByDir(file, --deep);
            } else if (name.matches(".*\\.(jpg|jpeg|png|gif|mp4|avi|mov|mkv|mpeg|3gp)$")) {
                String sha1 = FileUtils.getSha1(file);
                if (sha1 == null) {
                    return;
                }
                if (!assetsHashMap.containsKey(sha1)) {
                    assetsHashMap.put(sha1, new Assets(sha1, file.getAbsolutePath(), file.getName()));
                } else {
                    Assets assets = assetsHashMap.get(sha1);
                    // 相同文件直接删除
                    assert assets != null;
                    if (!Objects.equals(assets.path, file.getAbsolutePath())) {
                        FileUtils.deleteFile(file);
                    }
                }
            }
        }

    }

    public void clearNotUseAssets() {
        HashSet<String> toRemove = new HashSet<>();
        for (HashMap.Entry<String, Assets> entry : assetsHashMap.entrySet()) {
            if (entry.getValue().quote == 0) {
                FileUtils.deleteFile(entry.getValue().path);
                toRemove.add(entry.getKey());
            }
        }
        if (toRemove.size() > 0) {
            assetsHashMap.keySet().removeAll(toRemove);
        }
    }

    public ParseUIFromJson.MProgram getNextProgram() {
        programIndex = programIndex + 1 >= mPlayList.programs.length ? 0 : programIndex + 1;
        ParseUIFromJson.MProgram program = mPlayList.programs[programIndex];
        return program;
    }

    public ParseUIFromJson.MProgram getCurrentProgram() {
        ParseUIFromJson.MProgram program = mPlayList.programs[programIndex];
        return program;
    }
    public int getProgramCount() {
        if (mPlayList == null) {
            return 0;
        }
        return  mPlayList.programs.length;
    }

    public int getNextProgramIndex() {
        programIndex = programIndex + 1 >= mPlayList.programs.length ? 0 : programIndex + 1;
        return programIndex;
    }
}
